package com.gitee.wsl.ext.bitcode


fun Short.reverseBits(): Short {
    var num = this.toInt() and 0xFFFF // 确保处理16位无符号值
    var result = 0
    for (i in 0 until 16) {
        result = (result shl 1) or (num and 1)
        num = num ushr 1
    }
    return result.toShort()
}

/** Reverse the bits of [this] Int: abcdef...z -> z...fedcba */
fun Int.reverseBits(): Int {
    var v = this
    v = ((v ushr 1) and 0x55555555) or ((v and 0x55555555) shl 1) // swap odd and even bits
    v = ((v ushr 2) and 0x33333333) or ((v and 0x33333333) shl 2) // swap consecutive pairs
    v = ((v ushr 4) and 0x0F0F0F0F) or ((v and 0x0F0F0F0F) shl 4) // swap nibbles ...
    v = ((v ushr 8) and 0x00FF00FF) or ((v and 0x00FF00FF) shl 8) // swap bytes
    v = ((v ushr 16) and 0x0000FFFF) or ((v and 0x0000FFFF) shl 16) // swap 2-byte long pairs
    return v
}

fun Long.reverseBits(): Long {
    var x = this
    x = ((x ushr 1) and 0x5555555555555555) or ((x and 0x5555555555555555) shl 1)
    x = ((x ushr 2) and 0x3333333333333333) or ((x and 0x3333333333333333) shl 2)
    x = ((x ushr 4) and 0x0f0f0f0f0f0f0f0f) or ((x and 0x0f0f0f0f0f0f0f0f) shl 4)
    x = ((x ushr 8) and 0x00ff00ff00ff00ff) or ((x and 0x00ff00ff00ff00ff) shl 8)
    x = ((x ushr 16) and 0x0000ffff0000ffff) or ((x and 0x0000ffff0000ffff) shl 16)
    x = (x ushr 32) or (x shl 32)
    return x
}

